//
//  ZuoJComposeViewController.swift
//  Tanenbaum_blog
//
//  Created by Tanenbaum on 15/8/5.
//  Copyright © 2015年 GZJ. All rights reserved.
//

import UIKit
import SVProgressHUD
class ZuoJComposeViewController: UIViewController,UITextViewDelegate {

    
    
    let statusTextMaxLength = 140
    func dismiss() {
        
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    func selectPhoto() {
        
        view.removeConstraint(textViewBottomCon!)
        textViewBottomCon = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: photoSelectorVc.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomCon!)
        
        textView.resignFirstResponder()
        photoHeightCon?.constant = view.bounds.height * 0.6
        UIView.animateWithDuration(0.5) {
            
            self.view.layoutIfNeeded()
        }
        
        
    }
    func sendStatus() {
        
        let text = textView.emoticonText
        if text.characters.count > statusTextMaxLength {
            SVProgressHUD.showInfoWithStatus("您输入的内容过长", maskType: SVProgressHUDMaskType.Gradient)
            return
        }
        
        NetWorkTools.sharedTools.postStatus(text, image: photoSelectorVc.photos.last) { (result, error) -> () in
            if error != nil {
                
                SVProgressHUD.showInfoWithStatus("您的网络不给力", maskType: SVProgressHUDMaskType.Gradient)
            }
            self.dismiss()
        }
        
    }
    
    func inputEmoticon() {
 
        textView.resignFirstResponder()
        textView.inputView = (textView.inputView == nil) ? emotionVc.view : nil
        textView.becomeFirstResponder()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        addkeyboardOberserver()
    }
    
    deinit {
        removeKeyboardOberserver()
    }
    private func addkeyboardOberserver() {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    private func removeKeyboardOberserver() {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private var toolbarBottomCon: NSLayoutConstraint?
    func keyboardChanged(n: NSNotification) {
        
        let curve = n.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        toolbarBottomCon?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)
        UIView.animateWithDuration(duration) {
            
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }

    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if photoHeightCon?.constant == 0 {
            
            textView.becomeFirstResponder()
        }
        
    }
    
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.lightGrayColor()
        
        view.addSubview(textView)
        view.addSubview(photoSelectorVc.view)
        view.addSubview(toolbar)
        
        addChildViewController(photoSelectorVc)
        prepareNav()
        prepareToolbar()
        prepareTextView()
        prepareTextlengthView()
        preparePhotoSelector()
    }
    
    private func prepareTextlengthView() {
        
        view.addSubview(textLengthLabel)
        textLengthLabel.text = "140"
        textLengthLabel.sizeToFit()
        textLengthLabel.ff_AlignInner(type: ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -8, y: -8))
    }
    
    var textViewBottomCon:NSLayoutConstraint?
    private func prepareTextView() {
        
        textView.backgroundColor = UIColor.whiteColor()
        
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        
        let cons = textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: photoSelectorVc.view, size: nil)
        textViewBottomCon = textView.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        placeholderLabel.text = "分享新鲜事"
        placeholderLabel.sizeToFit()
        textView.addSubview(placeholderLabel)
        placeholderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
    }
    //设置toolbar
    private func prepareToolbar() {
        
     
        toolbar.backgroundColor = UIColor(white: 0.8, alpha:1.0)
       let con =  toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        toolbarBottomCon = toolbar.ff_Constraint(con, attribute: NSLayoutAttribute.Bottom)
        
        let itemSettings = [["imageName": "compose_toolbar_picture","action":"selectPhoto"],
        
                   ["imageName": "compose_mentionbutton_background"],
          
                   ["imageName": "compose_trendbutton_background"],
           
                   ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
         
                   ["imageName": "compose_addbutton_background"]]
        
         var items = [UIBarButtonItem]()
        
         for dict in itemSettings {
            
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"]))
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        }
        items.removeLast()
        
        toolbar.items = items
    }
    
    //导航栏设置
    private func prepareNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem (title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem (title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        
        let titleLabel = UILabel(color: UIColor.blackColor(), fontSize: 15)
        titleLabel.text = "发微博"
        titleLabel.sizeToFit()
        titleView.addSubview(titleLabel)
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        
        let nameLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 13)
        nameLabel.text = UserAccount.shareAccount?.name ?? ""
        nameLabel.sizeToFit()
        titleView.addSubview(nameLabel)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
    }
    
    //准备照片选择器
    var photoHeightCon: NSLayoutConstraint?
    private func preparePhotoSelector() {
        
        var s = UIScreen.mainScreen().bounds.size
        s.height = 0
        let con = photoSelectorVc.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: s)
        photoHeightCon = photoSelectorVc.view.ff_Constraint(con, attribute: NSLayoutAttribute.Height)
        
    }
    //MARK - 发送微博的代理方法
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeholderLabel.hidden = textView.hasText()
        
        let len = statusTextMaxLength - textView.text.characters.count
        textLengthLabel.text = String(len)
        textLengthLabel.textColor = len < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
        
        print(textView.text)
    }
    
    //MARK -- 懒加载控件
    private lazy var emotionVc: EmoticonViewController = EmoticonViewController { [weak self](emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
    }

    
    //添加文本视图
    private lazy var textView: UITextView = {
     
        
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //设置代理
        tv.delegate = self
        
        return tv
}()
    
    private lazy var photoSelectorVc: PhotoSelectorViewController = PhotoSelectorViewController()
    private lazy var placeholderLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
    private lazy var  toolbar = UIToolbar()
    
    private lazy var textLengthLabel: UILabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 12)
    
}
